from rest_framework import serializers
import re
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings
from celery_tasks.email.tasks import send_verify_email

from .models import User, Address
from goods.models import SKU


class CreateUserSerializer(serializers.ModelSerializer):

    """创建用户序列化器"""

    # 用户名，密码，密码2，手机号，短信验证码，同意条件
    # 定义要额外校验的字段：因为这些字段不在User模型类中
    password2 = serializers.CharField(label="确认密码", write_only=True)
    sms_code = serializers.CharField(label="短信验证码", write_only=True)
    allow = serializers.CharField(label="同意协议", write_only=True)

    # 补充token字段
    token = serializers.CharField(label="登录状态token", read_only=True)

    class Meta:
        model = User
        fields = ("id", "username", "password", "password2", "mobile", "sms_code", "allow", "token")
        extra_kwargs = {
            # 因为username和password是User(AbstractUser)中的字段，
            # 不能通过定义字段来验证它，
            # 所以要写在扩展校验中，添加约束条件
            "username":{
                "min_length":5,
                "max_length":20,
                "error_messages":{
                    "min_length":"仅允许5-20个字符的用户名",
                    "max_length":"仅允许5-20个字符的用户名"
                }
            },
            "password":{
                'write_only' : True,
                "min_length":5,
                "max_length":20,
                "error_messages":{
                    "min_length":"仅允许5-20个字符的密码",
                    "max_length":"仅允许5-20个字符的密码"
                }
            }
        }

    def validate_mobile(self, value):
        if not re.match(r"^1[3-9]\d{9}$", value):
            raise serializers.ValidationError("手机号格式不正确")

        return value

    def validate_allow(self, value):
        if value != "true":
            raise serializers.ValidationError("请同意协议")

        return value

    def validate(self, data):
        # 判断两次密码
        password = data["password"]
        password2 = data["password2"]
        if password != password2:
            raise serializers.ValidationError("两次密码不一致")
        
        # 判断短信验证码
        mobile = data["mobile"]
        sms_code = data["sms_code"]
        redis_conn = get_redis_connection("verify_codes")
        real_sms_code = redis_conn.get("sms_%s" % mobile)
        
        if real_sms_code is None:
            raise serializers.ValidationError("无效验证码")
        if sms_code != real_sms_code.decode():
            raise serializers.ValidationError("无效验证码")

        return data

    def create(self, validated_data):
        # 移除数据库模型类中不存在的属性
        del validated_data["password2"]
        del validated_data["sms_code"]
        del validated_data["allow"]
        user = super().create(validated_data)

        # 调用django的认证系统加密密码
        # 因为User继承自AbstractUser，所以自带了将密码加密的方式
        user.set_password(validated_data["password"])
        user.save()

        # 补充生成记录登录状态的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        user.token = token

        return user

class UserDetailSerializer(serializers.ModelSerializer):
    """用户详细信息序列化器"""
    class Meta:
        model = User
        # 只负责输出,并指定输出的字段
        fields = ("id", "username", "mobile", "email", "email_active")

class EmailSerializer(serializers.ModelSerializer):
    """邮箱序列化器"""
    class Meta:
        model = User
        fields = ("id", "email")
        extra_kwargs = {
            "email": {
                "required": True
            }
        }

    def update(self, instance, validated_data):
        instance.email = validated_data["email"]
        instance.save()

        # instance 就表示前面指定的User
        # 在完成保存数据的返回之前,生成邮件激活的链接
        verify_url = instance.generate_verify_email_url()

        # 发送激活邮件
        send_verify_email.delay(instance.email, verify_url)

        return instance

class UserAddressSerializer(serializers.ModelSerializer):
    """
    用户地址序列化器
    """
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ("user", "is_deleted", "create_time", "update_time")

    def validate_mobile(self, value):
        """
        验证手机号
        """
        if not re.match(r"^1[3-9]\d{9}$", value):
            raise serializers.ValidationError("手机号格式错误")

        return value

    def create(self, validated_data):
        """
        保存
        """
        validated_data["user"] = self.context["request"].user

        return super().create(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ("title")


class AddUserBrowseHistory(serializers.Serializer):
    """用户浏览记录序列化器"""
    sku_id = serializers.IntegerField(min_value=1, label="商品SKU编号")

    def validate_sku_id(self, value):
        """单独校验sku_id是否存在"""
        try:
            SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError("sku id 不存在")

        return value

    def create(self, validated_data):
        # 获取登录用户的user_id
        user_id = self.context["request"].user.id
        # 获取sku_id
        sku_id = validated_data['sku_id']
        # 获取连接到redis的对象
        redis_conn = get_redis_connection("history")

        # 使用管道,优化redis访问效率
        pl = redis_conn.pipeline()

        # 去重
        # lrem(name, count, value)
        pl.lrem("history_%s" % user_id, 0, sku_id)
        # 新增
        pl.lpush("history_%s" % user_id, sku_id)
        # 截取:截取最前面的五个元素
        pl.ltrim("history_%s" % user_id, 0, 4)

        # 执行
        pl.execute()

        return validated_data
